<?php

/**

 * 商品逻辑层

 * @author maniac

 */

namespace app\common\logic;



use app\common\model\GoodCategory;
use app\common\model\Goods AS GoodsModel;

use app\common\model\GoodSku;

use app\common\model\GoodAttrs;

use app\common\model\GoodAttrValue;

use app\common\model\Stores;
use app\facade\Options AS OptionsFacade;



class Goods extends Base

{

    /**

     * 重组提交信息

     * @param  array $data 请求的信息

     */

    public function recombine($data)

    {

        $data['store_id'] = isset($data['store_id']) && $data['store_id'] ? (int)$data['store_id'] : 0;
	$data['parameter'] = isset($data['parameter']) ? json_encode($data['parameter']) : '';

        if (isset($data['goods_sn']) && $data['goods_sn']) {

            $option        = unserialize(OptionsFacade::option('shop_info'));

            $goodsSnPrefix = isset($option['goods_sn_prefix']) && $option['goods_sn_prefix'] ? $option['goods_sn_prefix'] : '';

            $data['goods_sn'] = $goodsSnPrefix.$option['goods_sn_prefix'];

        }

        $this->validateData($data);

        $goods_album = [];

        if (isset($data['goods_album']) && !empty($data['goods_album'])) {

            foreach ($data['goods_album']['desc'] as $key => $val) {

                $goods_album[$key] = [

                    'value' => $data['goods_album']['value'][$key],

                    'desc'  => $val,

                ];

            }

        }

        $data['give_points']      = isset($data['give_points']) ? (float)$data['give_points'] : 0;

        $data['goods_album']      = serialize($goods_album);

        $data['goods_thumb_id']   = isset($data['goods_thumb_id']) ? (int)$data['goods_thumb_id'] : 0;

        $data['is_sale']          = isset($data['is_sale']) && $data['is_sale'] ? (int)$data['is_sale'] : 0;

        $data['is_latest']        = isset($data['is_latest']) && $data['is_latest'] ? (int)$data['is_latest'] : 0;

        $data['is_hot_sale']      = isset($data['is_hot_sale']) && $data['is_hot_sale'] ? (int)$data['is_hot_sale'] : 0;

        $data['is_recommand']     = isset($data['is_recommand']) && $data['is_recommand'] ? (int)$data['is_recommand'] : 0;

        $data['is_stock_visible'] = isset($data['is_stock_visible']) && $data['is_stock_visible'] ? (int)$data['is_stock_visible'] : 0;

        $data['goods_stock']      = $this->calcStock($data);

        unset($data['actual_sale_nums']);

        if (isset($data['goods_video']['name'])) {

            foreach ($data['goods_video']['name'] as $key => $val) {

                $arr[$key] = [

                    'value' => $data['goods_video']['value'][$key],

                    'name'  => $val,

                ];

            }

            $data['goods_video'] = serialize($arr);

        } else {

            $data['goods_video'] = '';

        }

        if (!isset($data['goods_detail']) || !trim($data['goods_detail'])) {

            exception('请输入商品详情');

        }

        return $data;

    }

    

    /**

     * 添加/编辑逻辑处理

     * @param  array $data 请求的信息

     */

    public function save($data)

    {

        if (isset($data['id']) && $data['id']) {

            // 编辑

            $info = GoodsModel::field('is_sale')->where('id', $data['id'])->find();

            // 上下架状态被改变，修改上下架时间

            if ($data['is_sale'] != $info['is_sale']) {

                $data['sale_time'] = time();

            }

        } else {

            $data['sale_time'] = time();

        }

        $sku = [];

        if (isset($data['sku'])) {

            $sku = $data['sku'];

            unset($data['sku']);

        }

        $attr = [];

        if (isset($data['attr'])) {

            $attr = $data['attr'];

            unset($data['attr']);

        }

        $result = parent::save($data);

        if ($result) {
//			$parent_id = GoodCategory::where('id',$data['category_id'])->value('parent_id');
//			$stores = Stores::field('id,category_id,type_id')->where('id',$data['store_id'])->find();
//			$category_id = explode(',',$stores['category_id']);
//			$type_id = explode(',',$stores['type_id']);
//			if(!in_array($data['category_id'],$type_id)){
//				$stores->type_id = trim($stores['type_id'].','.$data['category_id'],',');
//				if(!in_array($parent_id,$category_id)){
//					$stores->category_id = trim($stores['category_id'].','.$parent_id,',');
//				}
//				$stores->save();
//			}
//            $data['id'] = isset($data['id']) && $data['id'] ? $data['id'] : $result;

            if ($sku) {

                $this->updateSku($data['store_id'], $data['id'], $sku);

            }

            if ($attr) {

                $this->updateAttr($data['store_id'], $data['id'], $attr);

            }

        }

        return $result;

    }

    

    /**

     * 修改状态附件

     * @param  array $data 请求的信息

     */

    public function statusAttach($data)

    {

        $update = [

            'id'         => $data['id'],

            $data['key'] => $data['value'] ? 0 : 1,

        ];

        if ($data['key'] == 'is_sale') {

            $update['sale_time'] = time();

        }

        return $update;

    }

    

    private function validateData($data)

    {

        if (!isset($data['goods_name']) || trim($data['goods_name']) == '') {

            exception('请输入商品名称');

        }

        if (isset($data['goods_sn']) && $data['goods_sn'] && !isset($data['sku'])) {

            $option = 

            $where = [

                'store_id' => $data['store_id'],

                'goods_sn' => $data['goods_sn'],

            ];

            $info = GoodsModel::where($where)->find();

            if ($info) {

                exception('商品货号已存在');

            }

        }

        if (!isset($data['category_id']) || !$data['category_id']) {

            exception('请选择商品分类');

        }

        if (isset($data['sku'])) {

            foreach ($data['sku']['sale_price'] as $v) {

                if ((float)$v == false) {

                    exception('请完善商品 sku 属性的销售价');

                }

            }

        } elseif ((float)$data['sale_price'] == false) {

            exception('请输入商品销售价');

        }

    }

    

    /**

     * 计算商品库存

     * @param  array $data 请求的信息

     */

    private function calcStock($data)

    {

        if (!isset($data['sku']) || empty($data['sku']['stock'])) {

            if (!(int)$data['goods_stock']) {

                exception('请输入商品库存');

            }

            return (int)$data['goods_stock'];

        }

        $count = 0;

        foreach ($data['sku']['stock'] as $v) {

            $count += (int)$v;

        }

        if ($count == 0) {

            exception('请输入商品库存');

        }

        return $count;

    }

    

    /**

     * 编辑商品 sku 信息

     * @param  int   $store_id 店铺 id

     * @param  int   $goods_id 商品 id

     * @param  array $data     商品 sku 信息

     */

    private function updateSku($store_id, $goods_id, $data)
    {

        if ($goods_id && isset($data['sku_id']) && !empty($data['sku_id'])) {

            // 商品原始 sku

            $originSku = GoodSku::where(['store_id' => $store_id, 'goods_id' => $goods_id])->order('id ASC')->column('id');

            $deleteSku = array_values(array_diff($originSku, $data['id']));

            if (!empty($deleteSku)) {

            // 删除去除的 sku

                GoodSku::destroy($deleteSku);

            }

            

            // 获取商品 skuid 最后一个索引

            $index = count($data['sku_id']) - 1;

            $key   = 0;

            foreach ($data['sku_id'][$index] as $k => $v) {

                $update[$key] = [

                    'sku_sn'       => $data['sku_sn'][$k],

                    'sku_name'     => $data['sku_name'][$index][$k],

                    'cost_price'   => (float)$data['cost_price'][$k],

                    'market_price' => (float)$data['market_price'][$k],

                    'sale_price'   => (float)$data['sale_price'][$k],

                    'weight'   => (float)$data['weight'][$k],

                   'stock'        => (int)$data['stock'][$k],
		     'img'          => $data['img'][$k],				
                ];

                if (isset($data['id'][$k]) && $data['id'][$k]) {

                    // 存在主键 id，需要更新，传入更新条件

                    $update[$key]['id'] = $data['id'][$k];

                } else {

                    // 不存在主键 id，新增

                    $update[$key]['store_id'] = $store_id;

                    $update[$key]['goods_id'] = $goods_id;

                    $update[$key]['sku_id']   = $v;

                }

                $key++;

            }

            // 批量更新，根据是否存在更新条件来自动执行更新或添加

            (new GoodSku)->saveAll($update);

        }

    }

    

    /**

     * 编辑商品属性信息

     * @param  int   $store_id 店铺 id

     * @param  int   $goods_id 商品 id

     * @param  array $data     商品属性信息

     */

    private function updateAttr($store_id, $goods_id, $data)

    {

        if ($goods_id && !empty($data)) {

            // 获取数组所有索引，得到所有属性 id 值

            $keys  = array_keys($data);

            $where = [

                ['id', 'in', $keys],

            ];

            // 以 id 为索引，获取所有属性名称

            $attrs  = GoodAttrs::where($where)->column('name', 'id');

            $update = [];

            $index  = 0;

            $ids    = [];

            foreach ($data as $key => $val) {

                $update[$index] = [

                    'store_id'   => $store_id,

                    'goods_id'   => $goods_id,

                    'attr_id'    => $key,

                    'attr_name'  => $attrs[$key],

                    'attr_value' => isset($val['value']) && $val['value'] ? implode(',', $val['value']) : '',

                ];

                if (isset($val['id']) && $val['id']) {

                    $ids[] = $val['id'];

                    // 存在主键 id，需要更新，传入更新条件

                    $update[$index]['id'] = $val['id'];

                }

                $index++;

            }

            // 商品原始属性

            $originAttr = GoodAttrValue::where(['store_id' => $store_id, 'goods_id' => $goods_id])->order('id ASC')->column('id');

            $deleteAttr = array_values(array_diff($originAttr, $ids));

            if (!empty($deleteAttr)) {

                // 删除去除的 sku

                GoodAttrValue::destroy($deleteAttr);

            }

            // 批量更新，根据是否存在更新条件来自动执行更新或添加

            (new GoodAttrValue)->saveAll($update);

        }

    }

}

